<template>
	<div id="contract_details">
		<!-- 合同详细情况 -->
		<div class="body">
			<el-row class="title">
				<el-col :span="4">合同</el-col>
				<el-col :span="3" class="fr" v-if="this.$store.state.funtionType.indexOf('终止合同')>-1">
					 <el-button type="danger"  @click="overContract"  plain>终止合同</el-button>
				</el-col>
                <el-col :span="3" class="fr"  v-if="contract.conState.id==1 && this.$store.state.funtionType.indexOf('确认签订')>-1">
                    <el-button type="primary" plain @click="sign">确认签订</el-button>
                </el-col>
				<el-col  class="fr" :span="3"  v-if="contract.conState.id!=1">
					<el-button v-print="'#contractPrint'">打印订单</el-button>
				</el-col>
				<el-col  class="fr" :span="3"  v-if="contract.conState.id!=1">
					<el-button @click="toPrint">打印合同</el-button>
				</el-col>
                <el-col  class="fr" :span="3" v-if="contract.conState.id==1">
					<el-button @click="editContract" >编辑</el-button>
				</el-col>
                <el-col  class="fr" :span="3"  v-if="contract.conState.id==4">
					<el-button type="success" @click="finish" plain>完成</el-button>
				</el-col>
			</el-row>
			<el-form
				label-width="125px"
				class="demo-ruleForm save_contract_form"
				style="overflow:hidden;padding-top:20px"
			>
				<el-form-item label="合同名称：">
					{{contract.theme}}
				</el-form-item>
                <el-form-item label="合同编号：">
					{{contract.contractNum}}
				</el-form-item>
				<el-form-item label="对应客户：">
					{{contract.customer?contract.customer.customerName:"无"}}
				</el-form-item>
				<el-form-item label="对应机会：">
					{{contract.oppo?contract.oppo.oppoName:"无"}}
				</el-form-item>
				<el-form-item label="总金额：" class="inline__">
					{{contract.totalMoney?contract.totalMoney:0}}
				</el-form-item>
				<el-form-item label="分类：" class="inline__">
					{{contract.classify?contract.classify.name:"无"}}
				</el-form-item>
				<el-form-item label="付款方式：" class="inline__">
					{{contract.paymentMethod?contract.paymentMethod.name:"无"}}
				</el-form-item>
				<el-form-item label="开始结束时间：" class="inline__">
					{{contract.startTime?contract.startTime:"2000-00-00" | format_date}}&emsp;到&emsp;{{contract.overTime?contract.overTime:"2000-00-00" | format_date}}
				</el-form-item>
				<el-form-item label="所有者：" class="inline__">
					{{contract.owner?contract.owner.empName:'无'}}
				</el-form-item>
				<el-form-item label="开票金额：" class="inline__">
					{{contract.invoiceMoney?contract.invoiceMoney:0}}
				</el-form-item>
				<el-form-item label="客户签约人：" class="inline__">
					{{contract.customerSigner?contract.customerSigner:"无"}}
				</el-form-item>
				<el-form-item label="我方签约人：" class="inline__">
					{{contract.empSigner?contract.empSigner.empName:"无"}}
				</el-form-item>
				<el-form-item label="签约日期：" class="inline__">
					{{contract.signTime?contract.signTime:"2000-00-00" | format_date}}
				</el-form-item>
				<el-form-item label="结款方式：" class="inline__">
					{{contract.payMethod?contract.payMethod.name:"无"}}
				</el-form-item>
				<el-form-item label="状态：" class="inline__">
					{{contract.conState?contract.conState.name:"无"}}
				</el-form-item>
				<!--<el-form-item label="合同文件：" class="inline__">
                    <el-button type="text" v-if="contract.conFilesUrl" @click="download">下载</el-button>
                    <span type="text" v-if="!contract.conFilesUrl">无</span>
				</el-form-item>-->
				<el-form-item label="备注：">
					无
				</el-form-item>
			</el-form>
		</div>
		<!-- 产品 -->
		<div style="margin-top:10px;background-color:#ffffff;text-align:center">
			<el-row type="flex" justify="center">
				<el-col  :span="4" style="font-size:22px;color:#606266">产品订单</el-col>
			</el-row>
			<el-table  :data="contract.productList">
					<el-table-column label="图片" align="center" header-align="center">
						<template slot-scope="s">
							<el-image :src="s.row.proDetail.proImgSrc" style="width:40px;height:40px;"></el-image>
						</template>
					</el-table-column>
					<el-table-column prop="proDetail.product.productName" label="名称" align="center" header-align="center"></el-table-column>
					<el-table-column label="规格属性">
						<template slot-scope="s">
							<span v-for="item in s.row.proDetail.abilities" :key="item.abilityId">{{item.abilityName}} &emsp;</span>
						</template>
					</el-table-column>
					<el-table-column prop="proDetail.product.productBrand" label="品牌" align="center" header-align="center"></el-table-column>
					<el-table-column label="售价" align="center" header-align="center">
						<template slot-scope="s">
							<span>{{s.row.discount}}元</span>
						</template>
					</el-table-column>
					<el-table-column label="数量" prop="proCount" align="center" header-align="center">
					</el-table-column>
					<el-table-column label="金额" align="center" header-align="center">
						<template slot-scope="s">
							{{ s.row.discount * s.row.proCount }}
						</template>
					</el-table-column>
				</el-table>
		</div>
		<!-- 各种计划和记录的视图 -->
		<div class="project_show" v-if="contract.conState.id!=1">
			<el-row class="plan">
				<el-col :span="11" class="bg_white">
					交付计划
					<el-button type="text" size="mini" @click="openDeliveryPlan">
						<i class="iconfont icon-jiahao" />
					</el-button>
					<el-row v-for="dp in deliveryPlans" :key="dp.deliveryPlanId" style="line-height:28px">
						<el-button type="text" size="mini" @click="deliveryDetail(dp)" >{{ dp.deliveryTime.name }}</el-button>
						<span class="font_color">{{ isNew(dp)?"->已交付":"" }}</span>
						<span class="fl_right_font">{{ dp.deliveryPlanDate | format_date}}</span>
					</el-row>
				</el-col>
				<el-col :span="11" :offset="2" class="bg_white">
					回款计划
					<el-button type="text" size="mini" @click="openBackToArticlePlan" >
						<i class="iconfont icon-jiahao" />
					</el-button>
					<el-row v-for="r in returnmons" :key="r.returnId">
						<el-button type="text" size="mini" @click="returnDetails(r)" >{{ r.returnTimes.name }}{{ r.returnMoney?":￥"+r.returnMoney:"" }}</el-button>
						<span class="font_color">{{ isNewReturn(r)?"->已回款":"" }}</span>
						<span class="fl_right_font">{{ r.returnDate | format_date}}</span>
					</el-row>
				</el-col>
			</el-row>
			<el-row class="record">
				<el-col :span="11" class="bg_white" style="height:100%">
					交付记录
					<el-button type="text" size="mini" v-popover:popover>
						<i class="iconfont icon-jiahao" />
					</el-button>
					<el-popover ref="popover" placement="right" trigger="click">
						<el-row v-for="dp in deliveryPlans" :key="dp.deliveryPlanId">
							<el-link v-if="(!isNew(dp)) && dp.isOut == 2" @click="deliveryRecordDetails(dp)" :underline="false">创建 {{ dp.deliveryTime.name }} 交付记录</el-link>
						</el-row>
					</el-popover>
					<el-row v-for="dr in deliveryRecords" :key="dr.deliveryRecordId">
						<el-button type="text" size="mini" @click="editDeliveryRecord(dr)">{{ dr.deliveryPlan.deliveryTime.name }}</el-button>
						<span class="fl_right_font">{{ dr.delDate | format_date}}</span>
					</el-row>
				</el-col>
				<el-col :span="11" :offset="2" class="row bg_white">
					回款记录
					<el-button type="text" size="mini" v-popover:popoverReturn>
						<i class="iconfont icon-jiahao" />
					</el-button>
					<el-popover ref="popoverReturn" placement="right" trigger="click">
						<el-row v-for="r in returnmons" :key="r.returnId">
							<el-link v-if="!isNewReturn(r)" :underline="false" @click="addReturnRecord(r)">创建 {{ r.returnTimes.name }} 回款记录</el-link>
						</el-row>
					</el-popover>
					<el-row v-for="rr in returnRecords" :key="rr.returnRecordId">
						<el-button type="text" size="mini" @click="editReturnRecord(rr)">{{ rr.returnmon.returnTimes.name }}：{{ rr.returnMoney }}</el-button>
						<span v-if="rr.takeInvoice==2" class="el-icon-right">
							<el-button type="text" size="mini" style="color:#9999ff" @click="addInvoice(rr)">开票</el-button>
						</span>
						<span class="fl_right_font">{{ rr.realReturnDate | format_date}}</span>
					</el-row>
				</el-col>
			</el-row>
			<el-row class="row bg_white" style="margin-top:10px">
				开票记录
				<el-button type="text" size="mini" @click="conInvoiceRecordDialogVisible = true">
					<i class="iconfont icon-jiahao" />
				</el-button>
				<el-row v-for="cr in conInvoiceRecords" :key="cr.conInvoiceRecId">
					<el-button type="text" size="mini" @click="editConInvoice(cr)">{{ cr.invCon }}:￥{{ cr.invMoney }}</el-button>
					<span v-if="cr.isReturnMon==2" class="el-icon-right">
						<el-button type="text" size="mini" style="color:#9999ff" @click="addReturnPlan(cr)">回款计划</el-button>
					</span>
					<span class="fl_right_font">{{ cr.invBeginDate | format_date}}</span>
				</el-row>
			</el-row>
		</div>
		<!-- 新增和修改合同的弹窗 -->
		<el-dialog title="合同" :visible.sync="savaContractDialogVisible" width="60%" top="5vh" destroy-on-close>
			<save-contract ref="refSaveContract"></save-contract>
		</el-dialog>
		<!-- 回款计划弹窗 -->
        <el-dialog title="回款计划" :visible.sync="backToArticlePlanDialogVisible" width="60%" destroy-on-close>
            <back-article-plan ref="refBackToArticlePlan" :contract="contract" :_parent="this"></back-article-plan>
        </el-dialog>
		<!-- 回款记录弹窗 -->
        <el-dialog title="回款记录" :visible.sync="backToArticleRecordDialogVisible" width="60%" destroy-on-close>
            <back-article-record ref="refBackToArticleRecord" :contract="contract" :_parent="this"></back-article-record>
        </el-dialog>
		<!-- 交付计划弹窗 -->
        <el-dialog title="交付计划" :visible.sync="deliveryPlanDialogVisible" width="60%" destroy-on-close :before-close="deliveryPlanDialogBeforClose">
            <delivery-plan ref="refDeliveryPlan" :contract="contract" :_parent="this"></delivery-plan>
        </el-dialog>
		<!-- 交付记录弹窗 -->
        <el-dialog title="交付记录" :visible.sync="deliveryRecordDialogVisible" width="60%" destroy-on-close>
            <delivery-record ref="refDeliveryRecord" :contract="contract" :_parent="this"></delivery-record>
        </el-dialog>
		<!-- 开票记录弹窗 -->
        <el-dialog title="开票记录" :visible.sync="conInvoiceRecordDialogVisible" width="60%" destroy-on-close>
            <con-invoice-record ref="refConInvoiceRecord" :contract="contract" :_parent="this"></con-invoice-record>
        </el-dialog>
		<contract-print :contract="contract" style="position: relative;z-index:-1;"></contract-print>
	</div>
</template>

<script>
// 日期格式化插件
import {formatTimeToStr} from "../../assets/format"
import contractPrint from "./print"
export default {
	components: {
		'save-contract': resolve => require(["./save_contract"], resolve),		// 新增和修改组件标签
		'back-article-plan':resolve => require(["./back_to_article_plan"], resolve), // 回款计划
		'back-article-record':resolve => require(["./back_to_article_record"], resolve),	// 回款记录
		'delivery-plan':resolve => require(["./delivery_plan"], resolve),	// 交付计划
		'delivery-record':resolve => require(["./delivery_record"], resolve),	//交付记录
		'con-invoice-record':resolve => require(["./con_invoice_record"], resolve), // 开票记录
		'contract-print':contractPrint
	},
	data() {
		return {
			savaContractDialogVisible: false,  //合同新增和修改的弹窗控制开关
			backToArticlePlanDialogVisible:false,	// 回款计划弹窗开关
			backToArticleRecordDialogVisible:false,	// 回款记录弹窗开关
			deliveryPlanDialogVisible:false,	// 交付计划弹窗开关
			deliveryRecordDialogVisible:false,	// 交付记录弹窗开关
			conInvoiceRecordDialogVisible:false,// 开票记录弹窗开关
			contract: {},
			activeNames:['1'],					// 产品折叠面板控制
			deliveryPlans:[],					// 交付计划列表
			deliveryRecords:[],					// 交付记录列表
			returnmons:[],						// 回款计划列表
			returnRecords:[],					// 回款记录列表
			conInvoiceRecords:[],				// 开票记录列表

			deliveryPlan:{}		// 单个的交付计划，用于传入交付记录
		}
	},
	methods:{
        // 完成合同
        finish(){
            this.global.confirm(
                "提示",
                "是否确认终止合同？ 终止后不可对合同进行任何操作",
                () => {
                    this.contract.conState.id=5
                    this.contract.conState.name="已取消"
                    const loading = this.$loading({
                        lock: true,
                        text: '修改中',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0,0,0,0.5)'
                    });
                    this.axios.post('api/in-sale/contract',this.contract)
                    .then(() => {
                        loading.close()
                        this.$router.push('/contract-index')
                        this.global.mes_success("合同已完成");
                    })
                    .catch(() => {
                        loading.close()
                        this.global.mes_error("修改失败");
                    })
                },() => {
                    this.global.mes_message("取消操作");
                }
            )
        },
        // 终止合同
        overContract(){
            this.global.confirm(
                "提示",
                "是否确认终止合同？ 终止后不可对合同进行任何操作",
                () => {
                    this.contract.conState.id=6
                    this.contract.conState.name="已取消"
                    const loading = this.$loading({
                        lock: true,
                        text: '修改中',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0,0,0,0.5)'
                    });
                    this.axios.post('api/in-sale/contract',this.contract)
                    .then(() => {
                        loading.close()
                        this.$router.push('/contract-index')
                        this.global.mes_success("合同已终止");
                    })
                    .catch(() => {
                        loading.close()
                        this.global.mes_error("修改失败");
                    })
                },() => {
                    this.global.mes_message("取消操作");
                }
            )
        },
        // 确认签订合同
        sign(){
            this.global.confirm(
                "提示",
                "是否确认签订合同？",
                () => {
                    this.contract.conState.id=2
                    this.contract.conState.name="已签订"
                     const loading = this.$loading({
                        lock: true,
                        text: '修改中',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0,0,0,0.5)'
                    });
                    this.axios.post('api/in-sale/contract',this.contract)
                    .then(() => {
                        this.getContractById()
                        loading.close()
                        this.global.mes_success("修改成功");
                    })
                    .catch(() => {
                        loading.close()
                        this.global.mes_error("修改失败");
                    })
                },() => {
                    this.global.mes_message("取消签订");
                }
            )
        },
        // 文件下载
        download(){
            this.getUrlBase64(this.contract.conFilesUrl).then(base64 => {
                let link = document.createElement('a')
                link.href = base64
                link.download = 'qrCode.png'
                link.click()
            })
        },
        getUrlBase64(url) {
            return new Promise(resolve => {
                let canvas = document.createElement('canvas')
                let ctx = canvas.getContext('2d')
                let img = new Image()
                img.crossOrigin = 'Anonymous' //允许跨域
                img.src = url
                img.onload = function() {
                    canvas.height = 300
                    canvas.width = 300
                    ctx.drawImage(img, 0, 0, 300, 300)
                    let dataURL = canvas.toDataURL('image/png')
                    canvas = null
                    resolve(dataURL)
                }
            })
        },
		toPrint(){
			this.$store.dispatch('setContract',this.contract)
			this.$router.push('/template-contract')
		},
		// 打开回款计划弹框
		openBackToArticlePlan(){
			this.backToArticlePlanDialogVisible = true
			this.$nextTick(function(){
				this.$refs.refBackToArticlePlan.returnmons = this.returnmons
			})
		},
		// 由回款记录开票
		addInvoice(rr){
			this.conInvoiceRecordDialogVisible = true
			this.$nextTick(function(){
				this.$refs.refConInvoiceRecord.conInvoice.invMoney =  rr.returnMoney
				this.$refs.refConInvoiceRecord.conInvoice.isReturnMon = 1
				this.$refs.refConInvoiceRecord.returnRecord = this.global.copy_obj(rr)
			})
		},
		// 由开票记录添加回款计划
		addReturnPlan(cr){
			this.backToArticlePlanDialogVisible = true
			this.$nextTick(function(){
                this.$refs.refBackToArticlePlan.returnmons = this.global.copy_obj(this.returnmons)
				this.$refs.refBackToArticlePlan.returnMon.returnMoney = cr.invMoney
				this.$refs.refBackToArticlePlan.conInvoice = this.global.copy_obj(cr)
			})
		},
		// 修改开票记录
		editConInvoice(cr){
			this.conInvoiceRecordDialogVisible = true
			this.$nextTick(function(){
				this.$refs.refConInvoiceRecord.conInvoice = this.global.copy_obj(cr)
			})
		},
		// 修改回款记录
		editReturnRecord(rr){
			this.backToArticleRecordDialogVisible = true
			this.$nextTick(function(){
				this.$refs.refBackToArticleRecord.returnRecord = this.global.copy_obj(rr)
				this.$refs.refBackToArticleRecord.returnMon = this.global.copy_obj(rr.returnmon)
				this.$refs.refBackToArticleRecord.realReturnDatePicker.disabledDate = function(time){
					// 限制可选时间在回款计划制定之后，今天之前
					return time.getTime() < new Date(rr.returnmon.returnMakeDate) || time.getTime() > Date.now() - 8.64e6
				}
			})
		},
		// 添加回款记录
		addReturnRecord(r){
			this.backToArticleRecordDialogVisible = true
			this.$nextTick(function(){
				this.$refs.refBackToArticleRecord.returnMon = this.global.copy_obj(r)
				this.$refs.refBackToArticleRecord.realReturnDatePicker.disabledDate = function(time){
					// 限制可选时间在回款计划制定之后，今天之前
					return time.getTime() < new Date(r.returnMakeDate) || time.getTime() > Date.now() - 8.64e6
				}
			})
		},
		// 回款计划编辑按钮
		returnDetails(r){
			this.backToArticlePlanDialogVisible = true
			this.$nextTick(function(){
				this.$refs.refBackToArticlePlan.returnMon = this.global.copy_obj(r)
			})
		},
		// 交付记录编辑按钮
		editDeliveryRecord(dr){
			this.deliveryRecordDialogVisible = true
			this.$nextTick(function(){
				this.$refs.refDeliveryRecord.deliveryRecord = this.global.copy_obj(dr)
				this.$refs.refDeliveryRecord.deliveryPlan = this.global.copy_obj(dr.deliveryPlan)  
				this.$refs.refDeliveryRecord.pickerOptions.disabledDate = function(time){
					return time.getTime() < new Date(dr.deliveryPlan.deliveryMakeDate) || time.getTime() > Date.now() - 8.64e6
				}
			})
		},
		// 打开交付记录弹框 传入点击的交付计划对象, 新增按钮
		deliveryRecordDetails(dp){
			this.deliveryRecordDialogVisible = true
			this.$nextTick(function(){
				this.$refs.refDeliveryRecord.deliveryPlan = dp
				this.$refs.refDeliveryRecord.pickerOptions.disabledDate = function(time){
					return time.getTime() < new Date(dp.deliveryMakeDate) || time.getTime() > Date.now() - 8.64e6
				}
			})
		},
		// 打开所点击的交付计划详情
		deliveryDetail(dp){
			this.deliveryPlanDialogVisible = true
			this.$nextTick(function(){
				this.$refs.refDeliveryPlan.delivery = this.global.copy_obj(dp)
				dp.deliveryProLists.forEach(dpl => {
					this.contract.productList.forEach(pl => {
						if (dpl.productList.listId == pl.listId){
							pl.deliveryCount = dpl.deliveryCount
						}
					})
				})
			})
		},
        // 打开交付计划
        openDeliveryPlan(){
            this.deliveryPlanDialogVisible = true
        },
		// 编辑合同
		editContract(){
			this.savaContractDialogVisible = true
			this.$nextTick(function(){
                // 拷贝一个合同临时对象
				let _contract = this.global.copy_obj(this.contract)
				// 处理开始和结束时间
				_contract.startTime = [formatTimeToStr(_contract.startTime,"yyyy-MM-dd"),
					formatTimeToStr(_contract.overTime,"yyyy-MM-dd")]
				// 处理签约时间
				_contract.signTime = formatTimeToStr(_contract.signTime,"yyyy-MM-dd")
				// 赋值对象
				this.$refs.refSaveContract.contract = _contract
                this.$refs.refSaveContract.isDetail = this
            })	
		},
		// 获取初始化数据
		initData(){
			// 根据合同id获取所有交付计划
			this.$axios.get("api/in-sale/delivery/"+this.contract.contractId)
			.then(res => {
				this.deliveryPlans = res.data
			})
			.catch()
			// 根据合同id获取所有交付计录
			this.axios.get("api/in-sale/delivery-record/"+this.contract.contractId)
			.then(res => {
				this.deliveryRecords = res.data
			})
			.catch()
			// 根据合同id获取所有回款计划
			this.axios.get("api/in-sale/return-mon/"+this.contract.contractId)
			.then(res => {
				this.returnmons = res.data
			})
			.catch()
			// 根据合同id获取所有的回款记录
			this.axios.get("api/in-sale/returnRecord/"+this.contract.contractId)
			.then(res => {
				this.returnRecords = res.data
			})
			.catch(err => {
				console.error(err); 
			})
			// 根据合同id获取所有的开票记录
			this.axios.get("api/in-sale/conInvoiceRecord/"+this.contract.contractId)
			.then(res => {
				this.conInvoiceRecords = res.data
			})
			.catch(err => {
				console.error(err); 
			})
            // 根据合同id更新合同数据
            this.getContractById()
            
		},
		// 交付计划弹框关闭之前的操作
		deliveryPlanDialogBeforClose(done){
			this.contract.productList.forEach(pl => {
				delete pl.deliveryCount
			})
			done()
		},
		// 判断交付计划是否已经变成记录
		isNew(dp){
			let flag = false
			if(dp.deliveryPlanId){
				this.deliveryRecords.forEach(dr => {
					if(dr.deliveryPlan.deliveryPlanId == dp.deliveryPlanId ){
						flag = true
					}
				})
			}
			return flag
		},
		// 判断回款计划是否已经变成记录
		isNewReturn(r){
			let flag = false
			if(r.returnId){
				this.returnRecords.forEach(rr => {
					if(rr.returnmon.returnId == r.returnId ){
						flag = true
					}
				})
			}
			return flag
		},
        // 根据合同id更新合同数据
        getContractById(){
            this.axios.get("api/in-sale/contract/"+this.contract.contractId)
            .then(res => {
                this.contract = res.data
            })
        }
	},
	computed:{
		
	},
	created(){
		this.contract = JSON.parse(sessionStorage.getItem("contract"));
		sessionStorage.removeItem("contract")
		this.initData()
	},
	/* 路由守卫，拦截没有合同对象而直接进入 */
	beforeRouteEnter (to, from, next){
		if (sessionStorage.getItem("contract")){
			next()
		}else{
			next({path:"/contract-index"})
		}
	}
}
</script>

<style scoped>
#contract_details{margin: 0 auto; width: 1000px;}
#contract_details .top{margin: 0 auto;width: 100%}
.body{background-color: #ffffff;width: 100%;}
.save_contract_form .el-form-item{width: 100%;margin-bottom: 22px !important;}
.inline__{width:50%!important;display:inline-block}
.title{border-bottom: 1.5px solid #ababab;margin:0 10px}
.title .el-col{padding: 10px;font-size: 16px;line-height: 60px;}
.plan{margin-top: 10px;}
.record{margin-top: 10px;}
.bg_white{padding: 15px;background-color:white;}
.font_color{font-size: 12px;color: #ababab;}
.fl_right_font{font-size: 12px;float: right!important;}
.fr{float: right!important;}
</style>